import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios';

import { ElMessage } from 'element-plus';
import { resetRouter } from '@renderer/router/index';
// 创建 axios 实例
const service = axios.create({
  
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const accessToken = localStorage.getItem('token');
    if (accessToken) {
      config.headers.Authorization = accessToken;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { success, message, code } = response.data;

    if (success) {
      return response.data;
    }
    ElMessage({
      message: message,
      type: 'error'
    });

    // token 过期,重新登录
    if (code == 1011008) {
      localStorage.clear();
      resetRouter();
    }

    return Promise.reject(new Error(message || 'Error'));
    // // 响应数据为二进制流处理(Excel导出)
    // if (response.data instanceof ArrayBuffer) {
    //   return response;
    // }
  },
  (error: any) => {
    if (error.response.data) {
      console.log(error.response.data);

      const { code } = error.response.data;
      // token 过期,重新登录
      if (code == 1011008) {
        localStorage.clear();
        resetRouter();
      }
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
